package com.join.mybatis.method;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.join.mybatis.annotation.OneToMany;
import lombok.Getter;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author chengang
 */
@Getter
public class JoinField {

    private JoinColumnConfig joinClumnConfig;

    private String joinClumn;

    private String[] resultClumns;

    private Boolean allConvert=true;

    private String alias;

    private String sql;

    private String fieldName;

    private TableInfo joinTableInfo;

    private String joinTableClumn;

    private Class fieldClazz;

    private Boolean useJavaType;

    private Boolean lazy;

    public JoinField(JoinColumnConfig joinClumnConfig, Class<?> clazz) {
        this.joinClumnConfig = joinClumnConfig;
        this.joinClumn=joinClumnConfig.getJoinColumn();
        this.resultClumns=joinClumnConfig.getResultColumns();
        this.joinTableInfo=joinClumnConfig.getJoinTableInfo();
        this.fieldName=joinClumnConfig.getFieldName();
        this.joinTableClumn=joinClumnConfig.getJoinTableClumn();
        this.fieldClazz=joinClumnConfig.getFieldClass();
        this.useJavaType=joinClumnConfig.getUseJavaType();
        this.lazy=joinClumnConfig.getLazy();
        if(clazz.equals(OneToMany.class)){
            this.sql=convertDetaildSql();
        }else{
            this.sql=convertSql();
        }
    }

    private String convertSql(){
        if(useJavaType){
            return Arrays.stream(resultClumns).map(str->
                    String.format("%s.%s %s",fieldName,str,StrUtil.toCamelCase(joinTableInfo.getTableName()+"_"+str))).collect(Collectors.joining(","));
        }else{
            return  Arrays.stream(resultClumns).map(str->
                    "IFNULL(`"+fieldName+"`."+str+",'undefined')").collect(Collectors.joining(","));
        }
    }
    private String convertDetaildSql(){
        return Arrays.stream(resultClumns).map(str->
                String.format("%s",str)).collect(Collectors.joining(","));

    }
}
